var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;

// app.use(express.static('public'))

app.get('/', function (req: any, res: any) {
  // res.sendfile(__dirname + '/index.html');
  res.status(404).send('404 not found');
});

io.on('connection', function (socket: any) {
  console.log(`${io.eio.clientsCount} 用户链接已建立 <------- ` + socket.id + '\n');

  socket.on('login', function (data) {
    data.text = `用户  ${data.username}  加入了聊天室.........`;
    data.username = '';
    data.login = true;
    io.sockets.emit('broadcast', data); //  给所有客户端广播消息
  })


  socket.on('say', function (data: any) {
    if (data.username) {
      console.log(data);
      // socket.broadcast.emit('broadcast', data); //  向除当前连接外的客户发送消息
      io.sockets.emit('broadcast', data); //  给所有客户端广播消息
    }
  });


  socket.on('disconnect', function () {
    console.log(`\n---- X ---- X ---- 用户 ${socket.id} 已断开 ---- X ---- X ----\n`);
  });
});


server.listen(port, function () {
  console.log('\n\n\n\n\n\n\n\n\n\n\n\n');
  console.log(`server is listening on ${port}....\n`);
});
